package com.dualsportmaps.android;

import java.util.ArrayList;

import net.osmand.data.MapTileDownloader;
import net.osmand.data.MapTileDownloader.DownloadRequest;
import net.osmand.data.MapTileDownloader.IMapDownloaderCallback;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.ResourceManager.TileLoadDownloadRequest;
import net.osmand.plus.activities.OsmandApplication;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

import com.dualsportmaps.android.activities.CacheDsmMapTiles;

public class CacheDsmMapTilesService extends Service implements IMapDownloaderCallback {
	private final MapTileDownloader downloader = MapTileDownloader.getInstance();
	private final static int NOTIFICATION_SERVICE_ID = 2;
	public final static String DSMCACHE_STOP_SERVICE_ACTION  = "DSMCACHE_STOP_SERVICE_ACTION"; 
	private static WakeLock lockStatic;
	public final AsyncLoadingThread asyncLoader = new AsyncLoadingThread();
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		downloader.addDownloaderCallback(this);
		asyncLoader.start();
	}
	
	protected synchronized static PowerManager.WakeLock getLock(Context context) {
		if (lockStatic == null) {
			PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
			lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DsmCachingServiceLock");
		}
		return lockStatic;
	}

	@Override
	public void tileDownloaded(DownloadRequest req) {
		int count = DsmResourceManager.getDsmResourceManager((OsmandApplication)this.getApplicationContext()).tilesToCache.size();		
		if(req != null) {
			DsmResourceManager.getDsmResourceManager((OsmandApplication)this.getApplicationContext()).tilesToCache.remove(req.url);
			if(count % 20 == 0 || count == 1) {
				String ns = Context.NOTIFICATION_SERVICE;
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
				mNotificationManager.cancel(NOTIFICATION_SERVICE_ID+1);
				int icon = R.drawable.icon;
				CharSequence tickerText = count + " tiles left";
				if(count == 1)
					tickerText = "Tile downloads finished";
				long when = System.currentTimeMillis();
				Notification notification = new Notification(icon, tickerText, when);
				Context context = getApplicationContext();
				CharSequence contentTitle;
				CharSequence contentText;
				int idadd = 1;
				if(count > 1) {
					contentTitle = "Retrieving Tiles";
					contentText = count + " still to be downloaded.";
				} else {
					mNotificationManager.cancel(NOTIFICATION_SERVICE_ID);
					contentTitle = "Tile downloads finished";
					contentText = "Ride safe and keep your eyes on the trail!";
					idadd++;
				}
				Intent notificationIntent = new Intent(this, CacheDsmMapTiles.class);
				PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
				notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
				mNotificationManager.notify(NOTIFICATION_SERVICE_ID+idadd, notification);
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
			mNotificationManager.cancel(NOTIFICATION_SERVICE_ID);
			mNotificationManager.cancel(NOTIFICATION_SERVICE_ID+1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		downloader.removeDownloaderCallback(this);
		WakeLock lock = getLock(this.getApplicationContext());
		if (lock.isHeld()) {
			lock.release();
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			if(intent.getExtras().getBoolean("notify",true)) {
				String ns = Context.NOTIFICATION_SERVICE;
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
				int icon = R.drawable.icon;
				CharSequence tickerText = intent.getExtras().getString("mapname") + " tiles downloading";
				long when = System.currentTimeMillis();
				Notification notification = new Notification(icon, tickerText, when);
				Context context = getApplicationContext();
				CharSequence contentTitle = intent.getExtras().getString("mapname");
				CharSequence contentText = intent.getExtras().getInt("count") + " tiles to be downloaded.";
				Intent notificationIntent = new Intent(this, CacheDsmMapTiles.class);
				PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
				notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
				mNotificationManager.notify(NOTIFICATION_SERVICE_ID, notification);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.onStartCommand(intent, flags, startId);
	}
	private synchronized void requestDownload() {
		if(OsmandSettings.isInternetConnectionAvailable(DsmResourceManager.getApplicationContext()) && OsmandSettings.isUsingInternetToDownloadTiles(OsmandSettings.getPrefs(DsmResourceManager.getApplicationContext()))) {
			ArrayList<TileLoadDownloadRequest> list = new ArrayList<TileLoadDownloadRequest>(DsmResourceManager.getDsmResourceManager((OsmandApplication)this.getApplicationContext()).tilesToCache.values());
			for(int x = 0; x<6; x++) {
				if(list.size() > x)
					downloader.requestToDownload(list.get(x));
			}
		}
	}
	public class AsyncLoadingThread extends Thread {
		public AsyncLoadingThread(){
			super("DSM Map caching thread."); //$NON-NLS-1$
		}
		@Override
		public void run() {
			while(true){
				try {
					requestDownload();
					sleep(7000);
				} catch (InterruptedException e) {
				}
			}
		}
	}
}
